﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MvcMembership;
using System.Net.Mail;
using iDMS.Models;
using System.Web.Security;

namespace iDMS
{
    public class Mailer
    {
        private readonly ISmtpClient _smtpClient;

        private IDMSRepository db;

        public Mailer(IDMSRepository repository)
        {
            _smtpClient = new SmtpClientProxy();
            db = repository;
            
        }

        public void SendToEmployee(int id,string subject, string body)
        {
            Employee employee = db.EmployeesGetAll().Where(d => d.EmployeeID == id).SingleOrDefault();
            if (employee == null)
            {
                throw new ArgumentException();
            }
            if (!employee.UserGUID.HasValue)
            {
                throw new ArgumentException();
            }
            SendToUser(employee.UserGUID.Value, subject, body);
        }

        public void SendToRole(string role, string subject, string body)
        {
            if (!Roles.RoleExists(role))
            {
                throw  new ArgumentException();
            }
            string[] users = Roles.GetUsersInRole(role);
            MailMessage msg = new MailMessage();
            for (int i = 0; i < users.Length; i++)
            {
                MembershipUser user = Membership.GetUser(users[i]);
                msg.To.Add(user.Email);
            }
            msg.IsBodyHtml = false;
            msg.Body = body;
            msg.Subject = subject;
            _smtpClient.Send(msg);
        }

        public void SendToUser(Guid guid, string subject, string body)
        {
            MembershipUser user = Membership.GetUser(guid);
            MailMessage msg = new MailMessage();
            msg.To.Add(user.Email);
            msg.IsBodyHtml = false;
            msg.Body = body;
            msg.Subject = subject;
            _smtpClient.Send(msg);
        }

    }
}